package com.sddnytsh.body_buildingsystem.components

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ExitToApp
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import com.sddnytsh.body_buildingsystem.R
import com.sddnytsh.body_buildingsystem.config.NetworkConfig
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.topic.Profile
import com.sddnytsh.body_buildingsystem.components.SimpleAvatarImage
import com.sddnytsh.body_buildingsystem.components.DefaultAvatar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request

@Composable
fun Page4(navController: NavController) {
    // 使用UserState中的用户信息
    val currentUser = UserState.currentUser
    val userId = currentUser?.id ?: 0L
    var userName by remember { mutableStateOf(currentUser?.username ?: "未登录") }
    var userBio by remember { mutableStateOf("请先登录") }
    // 使用UserState中的头像，实现全局同步
    val userAvatar = UserState.currentUserAvatar

    // 定义颜色方案
    val primaryColor = Color(0xFF4361EE)
    val secondaryColor = Color(0xFF3A0CA3)
    val lightBackground = Color(0xFFF8F9FA)
    val cardColor = Color.White
    val textPrimary = Color(0xFF212529)
    val textSecondary = Color(0xFF6C757D)

    var isLoading by remember { mutableStateOf(true) }

    LaunchedEffect(currentUser) {
        if (currentUser != null) {
            userName = currentUser.username
            val profileData = fetchProfileData(currentUser.id)
            profileData?.let {
                userName = it.name
                userBio = it.des
                // 头像由UserState管理，不需要在这里设置
            }
        }
        isLoading = false
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(lightBackground)
    ) {
        // 顶部栏 - 使用渐变背景
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(64.dp)
                .background(
                    brush = Brush.linearGradient(
                        colors = listOf(primaryColor, secondaryColor)
                    )
                )
                .padding(horizontal = 16.dp)
        ) {
            Text(
                text = "个人中心",
                color = Color.White,
                style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold),
                modifier = Modifier.align(Alignment.Center)
            )
        }

        if (isLoading) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator(color = primaryColor)
            }
        } else {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .verticalScroll(rememberScrollState())
                    .padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // 用户信息卡片
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 8.dp),
                    colors = CardDefaults.cardColors(containerColor = cardColor),
                    shape = RoundedCornerShape(16.dp),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(20.dp)
                            .clickable(onClick = {
                                navController.navigate("profile") { popUpTo("main") { inclusive = false } }
                            }),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        // 用户头像
                        val currentAvatar = userAvatar
                        if (currentAvatar != null && currentAvatar.isNotEmpty()) {
                            SimpleAvatarImage(
                                avatarUrl = currentAvatar,
                                fallbackName = userName,
                                size = 80.dp
                            )
                        } else {
                            DefaultAvatar(
                                name = userName,
                                size = 80.dp
                            )
                        }

                        Spacer(modifier = Modifier.width(16.dp))

                        Column(
                            modifier = Modifier.weight(1f)
                        ) {
                            Text(
                                text = userName,
                                style = MaterialTheme.typography.titleMedium.copy(
                                    fontWeight = FontWeight.Bold,
                                    color = textPrimary
                                )
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = userBio,
                                style = MaterialTheme.typography.bodyMedium.copy(
                                    color = textSecondary
                                ),
                                maxLines = 2,
                                overflow = TextOverflow.Ellipsis
                            )
                        }

                        Icon(
                            imageVector = Icons.Default.KeyboardArrowRight,
                            contentDescription = "查看详情",
                            tint = textSecondary.copy(alpha = 0.6f)
                        )
                    }
                }

                Spacer(modifier = Modifier.height(20.dp))

                // 第一行功能按钮
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceEvenly
                ) {
                    // 我的发帖按钮
                    FunctionButton(
                        iconResId = R.drawable.forum,
                        title = "我的发帖",
                        subtitle = "查看我的帖子",
                        onClick = { navController.navigate("myPosts") },
                        primaryColor = primaryColor
                    )
                    
                    // 我的评论按钮
                    FunctionButton(
                        iconResId = R.drawable.comment,
                        title = "我的评论",
                        subtitle = "查看我的评论",
                        onClick = { navController.navigate("myComments") },
                        primaryColor = primaryColor
                    )
                    
                    // 关注的人按钮
                    FunctionButton(
                        iconResId = R.drawable.person,
                        title = "关注的人",
                        subtitle = "管理关注列表",
                        onClick = { navController.navigate("following") },
                        primaryColor = primaryColor
                    )
                }

                Spacer(modifier = Modifier.height(24.dp))

                // 功能区域1
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(containerColor = cardColor),
                    shape = RoundedCornerShape(16.dp),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                ) {
                    Column {
                        ProfileItem(
                            iconResId = R.drawable.pay,
                            text = "支付",
                            onClick = { /* 点击事件 */ },
                            primaryColor = primaryColor
                        )
                        Divider(
                            modifier = Modifier.padding(horizontal = 16.dp),
                            thickness = 0.5.dp,
                            color = lightBackground
                        )
                        ProfileItem(
                            iconResId = R.drawable.food,
                            text = "我的饮食",
                            onClick = { navController.navigate("diet") },
                            primaryColor = primaryColor
                        )
                        Divider(
                            modifier = Modifier.padding(horizontal = 16.dp),
                            thickness = 0.5.dp,
                            color = lightBackground
                        )
                        ProfileItem(
                            iconResId = R.drawable.star,
                            text = "我的收藏",
                            onClick = { navController.navigate("myFavorites") },
                            primaryColor = primaryColor
                        )
                    }
                }

                Spacer(modifier = Modifier.height(16.dp))

                // 功能区域2
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(containerColor = cardColor),
                    shape = RoundedCornerShape(16.dp),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                ) {
                    Column {
                        ProfileItem(
                            iconResId = R.drawable.settings,
                            text = "设置",
                            onClick = { navController.navigate("settings") },
                            primaryColor = primaryColor
                        )
                        Divider(
                            modifier = Modifier.padding(horizontal = 16.dp),
                            thickness = 0.5.dp,
                            color = lightBackground
                        )
                        ProfileItem(
                            iconResId = R.drawable.help,
                            text = "帮助与反馈",
                            onClick = { navController.navigate("help") },
                            primaryColor = primaryColor
                        )
                        Divider(
                            modifier = Modifier.padding(horizontal = 16.dp),
                            thickness = 0.5.dp,
                            color = lightBackground
                        )
                        ProfileItem(
                            iconResId = R.drawable.about,
                            text = "关于",
                            onClick = { navController.navigate("about") },
                            primaryColor = primaryColor
                        )
                    }
                }

                Spacer(modifier = Modifier.height(32.dp))

                // 退出登录按钮
                Button(
                    onClick = {
                        // 处理退出登录逻辑

                        navController.navigate("login") {
                            popUpTo("main") { inclusive = true }
                        }
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFFFFE0E0),
                        contentColor = Color(0xFFD32F2F)
                    ),
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(48.dp),
                    shape = RoundedCornerShape(12.dp),
                    elevation = ButtonDefaults.buttonElevation(
                        defaultElevation = 2.dp,
                        pressedElevation = 1.dp
                    )
                ) {
                    Icon(
                        imageVector = Icons.Default.ExitToApp,
                        contentDescription = "退出登录",
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("退出登录", fontWeight = FontWeight.Medium)
                }
            }
        }
    }
}

private suspend fun fetchProfileData(userId: Long): Profile? {
        val client = OkHttpClient.Builder()
            .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
            .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build()
    val request = Request.Builder()
        .url("${NetworkConfig.BASE_URL}/api/user-profile/$userId")
        .build()
    return withContext(Dispatchers.IO) {
        try {
            val response = client.newCall(request).execute()
            val body = response.body?.string() ?: return@withContext null
            val json = Gson().fromJson(body, JsonObject::class.java)
            if (json.get("success")?.asBoolean == true) {
                val data = json.getAsJsonObject("data")
                Profile(
                    userId = data.get("userId")?.asLong ?: userId,
                    name = data.get("name")?.asString ?: "用户",
                    des = data.get("des")?.asString ?: "",
                    gender = data.get("gender")?.asString ?: "保密",
                    height = data.get("height")?.asDouble ?: 0.0,
                    weight = data.get("weight")?.asDouble ?: 0.0,
                    birthday = data.get("birthday")?.asString ?: "1990-01-01",
                    location = data.get("location")?.asString ?: "未知"
                )
            } else null
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
}

@Composable
fun FunctionButton(
    iconResId: Int,
    title: String,
    subtitle: String,
    onClick: () -> Unit,
    primaryColor: Color
) {
    Card(
        modifier = Modifier
            .width(100.dp)
            .clickable { onClick() },
        colors = CardDefaults.cardColors(containerColor = Color.White),
        shape = RoundedCornerShape(16.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 图标
            Box(
                modifier = Modifier
                    .size(48.dp)
                    .clip(CircleShape)
                    .background(primaryColor.copy(alpha = 0.1f)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    painter = painterResource(id = iconResId),
                    contentDescription = title,
                    modifier = Modifier.size(24.dp),
                    tint = primaryColor
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 标题
            Text(
                text = title,
                style = MaterialTheme.typography.titleSmall.copy(
                    fontWeight = FontWeight.SemiBold,
                    color = Color(0xFF212529)
                ),
                textAlign = androidx.compose.ui.text.style.TextAlign.Center
            )
            
            Spacer(modifier = Modifier.height(4.dp))
            
            // 副标题
            Text(
                text = subtitle,
                style = MaterialTheme.typography.bodySmall.copy(
                    color = Color(0xFF6C757D)
                ),
                textAlign = androidx.compose.ui.text.style.TextAlign.Center,
                fontSize = 10.sp
            )
        }
    }
}
